#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的Markdown到HTML转换器
转换后的HTML可以在Word中打开并保存为.docx格式
"""

import re
import html

def convert_markdown_to_html(md_file_path, output_path):
    """将Markdown文件转换为HTML"""

    with open(md_file_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # HTML模板
    html_template = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>类小脑计算平台技术规格书</title>
    <style>
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            line-height: 1.6;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
        }
        h1, h2, h3, h4, h5, h6 {
            color: #2c3e50;
            margin-top: 2em;
            margin-bottom: 1em;
        }
        h1 { font-size: 2.5em; border-bottom: 3px solid #3498db; padding-bottom: 10px; }
        h2 { font-size: 2em; border-bottom: 2px solid #3498db; padding-bottom: 8px; }
        h3 { font-size: 1.5em; color: #34495e; }
        h4 { font-size: 1.3em; color: #34495e; }
        h5 { font-size: 1.1em; color: #34495e; }
        h6 { font-size: 1em; color: #34495e; }

        code {
            background-color: #f8f9fa;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: "Consolas", "Monaco", monospace;
            font-size: 0.9em;
        }

        pre {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 15px;
            overflow-x: auto;
            margin: 1em 0;
        }

        pre code {
            background: none;
            padding: 0;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            margin: 1em 0;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        ul, ol {
            margin: 1em 0;
            padding-left: 2em;
        }

        li {
            margin: 0.5em 0;
        }

        blockquote {
            border-left: 4px solid #3498db;
            margin: 1em 0;
            padding-left: 1em;
            color: #666;
        }

        hr {
            border: none;
            border-top: 2px solid #eee;
            margin: 2em 0;
        }

        .ascii-art {
            font-family: "Consolas", "Monaco", monospace;
            white-space: pre;
            background-color: #f8f9fa;
            padding: 15px;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
{content}
</body>
</html>"""

    # 转换Markdown内容
    html_content = convert_md_content(content)

    # 生成完整HTML
    full_html = html_template.format(content=html_content)

    # 保存HTML文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(full_html)

    print(f"转换完成！HTML文件已保存到: {output_path}")
    print("您可以：")
    print("1. 用浏览器打开HTML文件查看效果")
    print("2. 在Word中打开HTML文件，然后另存为.docx格式")
    print("3. 使用在线转换工具将HTML转换为Word")

def convert_md_content(content):
    """转换Markdown内容为HTML"""
    lines = content.split('\n')
    html_lines = []
    in_code_block = False
    code_lang = ''
    in_table = False
    table_rows = []

    i = 0
    while i < len(lines):
        line = lines[i]

        # 代码块处理
        if line.startswith('```'):
            if in_code_block:
                # 结束代码块
                html_lines.append('</code></pre>')
                in_code_block = False
            else:
                # 开始代码块
                code_lang = line[3:].strip()
                if any(keyword in line.lower() for keyword in ['ascii', 'art', '+-', '|']):
                    html_lines.append('<div class="ascii-art">')
                else:
                    html_lines.append(f'<pre><code class="language-{code_lang}">')
                in_code_block = True
            i += 1
            continue

        if in_code_block:
            if any(keyword in line for keyword in ['+-', '|', '┌', '└', '├', '│']):
                if not html_lines[-1].startswith('<div class="ascii-art">'):
                    html_lines[-1] = '<div class="ascii-art">'
                html_lines.append(line)
                if i == len(lines) - 1 or lines[i + 1].startswith('```'):
                    html_lines.append('</div>')
            else:
                html_lines.append(line)
            i += 1
            continue

        # 表格处理
        if '|' in line and line.strip().startswith('|'):
            if not in_table:
                in_table = True
                table_rows = []
            table_rows.append(line.strip())
            i += 1
            continue
        else:
            if in_table:
                # 结束表格
                html_lines.append(convert_table(table_rows))
                in_table = False
                table_rows = []

        # 标题
        if line.startswith('#'):
            level = 0
            for char in line:
                if char == '#':
                    level += 1
                else:
                    break
            content = line[level:].strip()
            html_lines.append(f'<h{level}>{content}</h{level}>')

        # 分隔线
        elif re.match(r'^-{3,}$', line.strip()):
            html_lines.append('<hr>')

        # 列表项
        elif re.match(r'^\s*[-*+]\s+', line):
            content = re.sub(r'^\s*[-*+]\s+', '', line)
            html_lines.append(f'<ul><li>{content}</li></ul>')

        # 数字列表
        elif re.match(r'^\s*\d+\.\s+', line):
            content = re.sub(r'^\s*\d+\.\s+', '', line)
            html_lines.append(f'<ol><li>{content}</li></ol>')

        # 空行
        elif not line.strip():
            html_lines.append('<br>')

        # 普通段落
        else:
            # 处理行内代码
            line = re.sub(r'`([^`]+)`', r'<code>\1</code>', line)
            # 处理粗体
            line = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', line)
            # 处理斜体
            line = re.sub(r'\*([^*]+)\*', r'<em>\1</em>', line)

            html_lines.append(f'<p>{line}</p>')

        i += 1

    # 处理最后的表格
    if in_table and table_rows:
        html_lines.append(convert_table(table_rows))

    return '\n'.join(html_lines)

def convert_table(table_rows):
    """转换表格"""
    if not table_rows:
        return ''

    # 解析表格数据
    parsed_rows = []
    for row in table_rows:
        cells = [cell.strip() for cell in row.strip('|').split('|')]
        if cells and any(cell.strip() for cell in cells):
            if not all(re.match(r'^[-:]+$', cell.strip()) for cell in cells):
                parsed_rows.append(cells)

    if not parsed_rows:
        return ''

    # 生成HTML表格
    html = ['<table>']

    # 第一行作为表头
    if parsed_rows:
        html.append('<thead><tr>')
        for cell in parsed_rows[0]:
            html.append(f'<th>{cell}</th>')
        html.append('</tr></thead>')

    # 其余行作为表体
    if len(parsed_rows) > 1:
        html.append('<tbody>')
        for row in parsed_rows[1:]:
            html.append('<tr>')
            for cell in row:
                html.append(f'<td>{cell}</td>')
            html.append('</tr>')
        html.append('</tbody>')

    html.append('</table>')
    return '\n'.join(html)

if __name__ == "__main__":
    input_file = "cerebellar_platform_spec_ui_upgraded(1).md"
    output_file = "cerebellar_platform_spec_ui_upgraded.html"

    try:
        convert_markdown_to_html(input_file, output_file)
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
